package com.zhugang.week13.hash;

import java.util.Arrays;

/**
 * @program algorithms
 * @description: isAnagram
 * @author: chanzhugang
 * @create: 2022/12/06 14:42
 */
public class IsAnagram {

    /**
     * 242 有效的字母异位词
     * https://leetcode.cn/problems/valid-anagram/
     *
     * @param s
     * @param t
     * @return
     */
    public boolean isAnagram(String s, String t) {
        /**
         * 和字符重排相同
         * 异位词：每个字符出现的次数都相同
         */
        if (s.length() != t.length()) {
            return false;
        }
        char[] array1 = s.toCharArray();
        char[] array2 = t.toCharArray();
        Arrays.sort(array1);
        Arrays.sort(array2);
        return Arrays.equals(array1, array2);
    }

    public boolean isAnagram2(String s, String t) {
        /**
         * 字符映射到数组，类似哈希思想
         */
        if (s.length() != t.length()) {
            return false;
        }
        int[] nums1 = new int[26];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            nums1[c - 'a']++;
        }

        int[] nums2 = new int[26];
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            nums2[c - 'a']++;
        }

        // 比较数组
        for (int i = 0; i < 26; i++) {
            if (nums1[i] != nums2[i]) {
                return false;
            }
        }
        return true;
    }
}